package com.xust.oa.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JwtUtil {
    //用户名称
    private static final String USERNAME = "zhangjie";

    // 签名加密的密钥
    private static final String SECRET_KEY = "123456";

    public static final int TOKEN_TIME_OUT = 1000 * 60 * 60 * 24;

    public static String getToken(String userId,String role) {
        // 获取jwt生成器
        JWTCreator.Builder builder = JWT.create();
        // 由于该生成器设置Header的参数为一个<String,Object>的Map,所以我们提前设置好
        Map<String, Object> header = new HashMap<>();
        header.put("typ", "JWT");  // 设置token的type为jwt
        header.put("alg", "HS384"); // 设置token的加密算法
        // 开始生成token
        String token = builder.withHeader(header)
                // 设置用户Id
                .withClaim("userId", userId)
                // token失效时间
                .withClaim("role",role)
                .withExpiresAt(new Date(System.currentTimeMillis() + TOKEN_TIME_OUT))
                // jwt发行时间，一般为系统时间
                .withIssuedAt(new Date(System.currentTimeMillis()))
                // token发行者名称（可自定义）
                .withIssuer(USERNAME)
                // 选择签名和加密算法
                .sign(Algorithm.HMAC384(SECRET_KEY));
        return token;
    }

    public static boolean verify(String token) {
        try {
            // 创建JWT验证器
            JWTVerifier verifier = JWT.require(Algorithm.HMAC384(SECRET_KEY))
                    .withIssuer(USERNAME) // 验证发行者名称
                    .build();
            // 解析并验证token
            verifier.verify(token);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public static String getUserIdFromToken(String token) {
        try {
            Algorithm algorithm = Algorithm.HMAC384(SECRET_KEY);
            JWTVerifier verifier = JWT.require(algorithm)
                    .withIssuer(USERNAME) // 验证发行者名称
                    .build();
            // 解析并验证token
            DecodedJWT jwt = verifier.verify(token);
            return jwt.getClaim("userId").asString();
        } catch (Exception e) {
            // 处理解析异常
            throw new RuntimeException("Invalid token", e);
        }
    }

    public static String getUserRoleFromToken(String token) {
        try {
            Algorithm algorithm = Algorithm.HMAC384(SECRET_KEY);
            JWTVerifier verifier = JWT.require(algorithm)
                    .withIssuer(USERNAME) // 验证发行者名称
                    .build();
            // 解析并验证token
            DecodedJWT jwt = verifier.verify(token);
            return jwt.getClaim("role").asString();
        } catch (Exception e) {
            // 处理解析异常
            throw new RuntimeException("Invalid token", e);
        }
    }
}
